package com.liang.lollipop.lreader.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.liang.lollipop.lreader.bean.HistorBean;

import java.util.ArrayList;

/**
 * Created by Lollipop on 2017/09/13.
 * 历史纪录的表
 */
public class HistorDAO {

    private Context context;
    private DBUtil dbUtil;

    private static final int PAGE_SIZE = 50;

    public HistorDAO(Context context) {
        this.context = context;
        dbUtil = new DBUtil(context);
    }

    public long insert(HistorBean bean){
        SQLiteDatabase database = dbUtil.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(DBUtil.HISTORY_NAME,bean.name);
        contentValues.put(DBUtil.HISTORY_PKG,bean.pkg);
        contentValues.put(DBUtil.HISTORY_TIME,bean.time);
        return database.insert(DBUtil.HISTORY_TABLE,null,contentValues);
    }

    public int delete(int id){
        SQLiteDatabase database = dbUtil.getWritableDatabase();
        return database.delete(DBUtil.HISTORY_TABLE,DBUtil.HISTORY_ID+" = ?",new String[]{String.valueOf(id)});
    }

    public int deleteAll(){
        SQLiteDatabase database = dbUtil.getWritableDatabase();
        return database.delete(DBUtil.HISTORY_TABLE,null,null);
    }

    public ArrayList<HistorBean> selectByPage(int page){
        SQLiteDatabase database = dbUtil.getReadableDatabase();
        ArrayList<HistorBean> beanList = new ArrayList<>();
        Cursor cursor = database.query(DBUtil.HISTORY_TABLE,
                new String[]{DBUtil.HISTORY_ID,DBUtil.HISTORY_NAME,DBUtil.HISTORY_PKG,DBUtil.HISTORY_TIME},
                null,null,null,null,DBUtil.HISTORY_ID+" desc",String.valueOf(PAGE_SIZE*page)+" , "+String.valueOf(PAGE_SIZE*(page+1)));
        while(cursor.moveToNext()){
            HistorBean bean = new HistorBean();
            bean.id = cursor.getInt(cursor.getColumnIndex(DBUtil.HISTORY_ID));
            bean.name = cursor.getString(cursor.getColumnIndex(DBUtil.HISTORY_NAME));
            bean.time = cursor.getString(cursor.getColumnIndex(DBUtil.HISTORY_TIME));
            bean.pkg = cursor.getString(cursor.getColumnIndex(DBUtil.HISTORY_PKG));
            beanList.add(bean);
        }
        cursor.close();
        return beanList;
    }

}
